package com.py.framework.core.rest.support.jsonserializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
	public final static ObjectMapper mapper = new ObjectMapper(); 
	
	/**
	 * json字符串转List<bean>
	 * @param json
	 * @param collectionClass
	 * @param elementClasses
	 * @return
	 */
	public static List<?> getObjectList(String json,Class<?> collectionClass, Class<?>... elementClasses){
		JavaType javaType = getCollectionType(ArrayList.class, elementClasses); 
		try {
			return mapper.readValue(json, javaType);
		} catch (JsonParseException e) { 
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * list转json
	 */
	public static String getJsonFromObject(Object object){
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	 /**   
    * 获取泛型的Collection Type  
    * @param collectionClass 泛型的Collection   
    * @param elementClasses 元素类   
    * @return JavaType Java类型   
    * @since 1.0   
    */   
	 @SuppressWarnings("deprecation")
	private  static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
	     return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   
	 }
}
